import { useContext, useReducer, useEffect } from "react";
import { ReduxContext } from "./Context";

export function useDispatch() {
      const store = useContext(ReduxContext);
      return store.dispatch;
}

export function useSelector(selector) {
      const store = useContext(ReduxContext);
      let { getState, subscribe } = store;
      let selectState = selector(getState());

      // 需要这个进行数据刷新
      const [, forceUpdate] = useReducer((x) => x + 1, 0);

      useEffect(() => {
            let unSubscribe = subscribe(() => {
                  forceUpdate();
            });

            return () => {
                  unSubscribe();
            };
      }, []);

      return selectState;
}
